<template>
  <div id="editVm" style="height: 100%">
    <el-form ref="editVm" :model="editVmData" label-width="120px">
      <el-tabs type="border-card" ref="vmTabs" v-model="currentTabName" :tab-position="tabPosition" :before-leave="checkTabs" style="height:100%">
        <el-tab-pane v-for="item in editableTabs" :key="item.name" :label="item.title" :name="item.name" :lazy="isLazyTab">
          <component :is="item.content" v-bind="$attrs" v-on="$listeners" ref="tabsCon" :hostData="hostData" :modetype="modetype2" :vmData="editVmData" :options="operateOptions" :osInfo="osInfo" @changeAddOrDel="changeAddOrDel" @updateVmDate="updateVmDate">
          </component>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <div id="addHardOperation" class="popOpera" v-if="modetype2 === 'editVm' || modetype2 === 'addVm'">
      <ul class="operate">
        <li @click="addHard">添加硬件</li>
        <li @click="delHard" :class="disableDelHardBtn ? 'disabled' : ''">删除硬件</li>
      </ul>
    </div>
  </div>
</template>
<script>
export default {
  name: 'editVm',
  props: {
    vmData: {
      type: Object
    },
    modetype: {},
    osInfoFromAdd: {
      type: Object
    }
  },
  data() {
    return {
      modetype2: this.modetype ? this.modetype : 'editVm',
      isLazyTab: !(this.modetype === 'addVm' || this.modetype === 'importVm'),
      hostData: {},
      editVmData: this.vmData,
      osInfo: null,
      currentTabName: 'options',
      tabPosition: 'left',
      editTableMap: new Map(),
      disableDelHardBtn: true,
      operateOptions: {
        addNew: false,
        delOne: false,
        type: '',
        currentTabName: this.currentTabName
      },
      addHardList: [{
        text: '网卡',
        clickFun: this.addNewNet
      }, {
        text: '新磁盘',
        disabled: this.vmData.enableReplicate && (this.vmData.status === this.enums.VmStateEnum.STARTED) || (this.vmData.cdpInfo && this.vmData.cdpInfo.enableCDP),
        clickFun: this.addNewDisk
      }, {
        text: '现有磁盘',
        disabled: this.vmData.enableReplicate || this.vmData.cdpInfo && this.vmData.cdpInfo.enableCDP,
        clickFun: this.addOldDisk
      }, {
        text: '裸磁盘',
        disabled: this.vmData.enableReplicate || this.vmData.cdpInfo && this.vmData.cdpInfo.enableCDP,
        clickFun: this.addBlockDisk
      }, {
        text: 'USB',
        clickFun: this.addUsb
      }, {
        text: 'GPU',
        disabled: this.vmData.status && this.vmData.status === this.enums.VmStateEnum.STARTED,
        clickFun: this.addGpu
      }, {
        text: 'PCIE',
        disabled: !this.vmData.status || (this.vmData.status === this.enums.VmStateEnum.STARTED ||
          this.vmData.systemVmType !== 'SCVM' && this.vmData.systemVmType !== 'SSA'),
        clickFun: this.addPCI
      }, {
        text: 'FPGA',
        clickFun: this.addFPGA
      }],
      defaultTabs: [{
        title: '摘要',
        name: 'options',
        content: () => import('../../vm/components/options')
      }, {
        title: 'CPU',
        name: 'CPUPart',
        content: () => import('../../vm/components/cpu')
      }, {
        title: '内存',
        name: 'MemoryPart',
        content: () => import('../../vm/components/memory')
      }, {
        title: '网卡',
        name: 'NetPart',
        content: () => import('../../vm/components/network')
      }, {
        title: '磁盘',
        name: 'DiskPart',
        content: () => import('../../vm/components/disk')
      }, {
        title: '光驱',
        name: 'CDPart',
        content: () => import('../../vm/components/cdrom')
      }, {
        title: '软驱',
        name: 'FPPart',
        content: () => import('../../vm/components/floppy')
      }, {
        title: '显卡',
        name: 'GHCARDPart',
        content: () => import('../../vm/components/ghcard')
      }],
      editTableTabs: []
    };
  },
  created: function() {
    this.osInfo = this.osInfoFromAdd;
    let that = this;
    if (this.modetype2 === 'editVm') {
      this.ser.get('vms/' + this.vmData.id).then(data => {
        that.editVmData = data.data;
        that.editVmData.vncPasswd = that.utils.decryptByAESModeCBC(that.editVmData.vncPasswd);
        this.ser.get('hosts/' + that.editVmData.hostId).then(data => {
          that.hostData = data.data;
        });
        this.setTabArray();
        this.setDefaultStorage();
      });
    } else {
      this.ser.get('hosts/' + that.vmData.hostId).then(data => {
        that.hostData = data.data;
      });
      this.setTabArray();
    }
  },
  mounted: function() {},
  watch: {
    currentTabName: function() {
      this.isShowDel();
      this.operateOptions.currentTabName = this.currentTabName;
    }
  },
  methods: {
    setTabArray() {
      this.defaultTabs.forEach(x => {
        this.editTableMap.set(x.name, x);
      });
      if (this.modetype2 === 'importVm') {
        this.editableTabs = this.defaultTabs.splice(0, 5);
        return;
      } else if (this.modetype2 === 'addVm') {
        this.editableTabs = [...this.editTableMap.values()];
        return;
      } else if (this.modetype2 === 'editVmTep') {
        this.editableTabs = this.defaultTabs.splice(0, 3);
        return;
      }
      // 编辑虚拟机
      if (this.editVmData.nics && !this.editVmData.nics.length) {
        this.editTableMap.delete('NetPart');
      }
      if (this.editVmData.usbs && this.editVmData.usbs.length && !this.editTableMap.has('USBPart')) {
        this.addTab('USBPart', false);
      }
      if (this.editVmData.gpus && this.editVmData.gpus.length && !this.editTableMap.has('vmGPUPart')) {
        this.addTab('vmGPUPart', false);
      }
      if (this.editVmData.vmPcis && this.editVmData.vmPcis.length && !this.editTableMap.has('PCIPart')) {
        this.addTab('PCIPart', false);
      }
      if (this.editVmData.fpgas && this.editVmData.fpgas.length && !this.editTableMap.has('FPGAPart')) {
        this.addTab('FPGAPart', false);
      }

      this.editableTabs = [...this.editTableMap.values()];
      return;
    },
    addTab: function(partName, show) {
      if (partName === 'USBPart') {
        this.editTableMap.set('USBPart', {
          title: 'USB',
          name: 'USBPart',
          content: () => import('../../vm/components/usb')
        });
      } else if (partName === 'DiskPart') {
        this.editTableMap.set('DiskPart', {
          title: '磁盘',
          name: 'DiskPart',
          content: () => import('../../vm/components/disk')
        });
      } else if (partName === 'NetPart') {
        this.editVmData.nics = [];
        this.editTableMap.set('NetPart', {
          title: '网卡',
          name: 'NetPart',
          content: () => import('../../vm/components/network')
        });
      } else if (partName === 'vmGPUPart') {
        this.editTableMap.set('vmGPUPart', {
          title: 'GPU',
          name: 'vmGPUPart',
          content: () => import('../../vm/components/gpu')
        });
      } else if (partName === 'PCIPart') {
        this.editTableMap.set('PCIPart', {
          title: 'PCIE',
          name: 'PCIPart',
          content: () => import('../../vm/components/pci')
        });
      } else if (partName === 'FPGAPart') {
        this.editTableMap.set('FPGAPart', {
          title: 'FPGA',
          name: 'FPGAPart',
          content: () => import('../../vm/components/fpga')
        });
      }
      this.editableTabs = [...this.editTableMap.values()];
      if (show) {
        this.currentTabName = partName;
      }
    },
    delTab: function(partName) {
      this.editTableMap.delete(partName);
      this.editableTabs = [...this.editTableMap.values()];
      this.currentTabName = 'options';
    },
    isShowDel: function() {
      if (this.currentTabName === 'options' || this.currentTabName === 'CPUPart' ||
        this.currentTabName === 'MemoryPart' || this.currentTabName === 'CDPart' ||
        this.currentTabName === 'FPPart' || this.currentTabName === 'GHCARDPart') {
        this.disableDelHardBtn = true;
      } else {
        this.disableDelHardBtn = false;
      }
    },
    delHard: function() {
      this.operateOptions.delOne = true;
    },
    beforeAddHard: function() {
      let that = this;
      let len = this.$refs.tabsCon.length;
      for (let i = 0; i < len; i++) {
        if (this.$refs.tabsCon[i].ref === this.currentTabName) {
          return new Promise((resolve, reject) => {
            let data = {
              canSumit: true
            };
            this.V.$validateAll(this.$refs.tabsCon[i].$el).then((success) => {
              let returnData = success || data;
              if (!returnData.canSumit) {
                that.$vConfirm({
                  content: '',
                  confirmType: that.enums.ConfirmEnum.INFO_WARNING_ONE,
                  confirm: function() {}
                });
              }
              resolve(returnData);
            }, (error) => {
              reject(error || data);
            });
          });
        }
      }
      return true;
    },
    addUsb: function() {
      this.beforeAddHard().then(res => {
        if (res.canSumit) {
          if (!this.editTableMap.has('USBPart')) {
            this.addTab('USBPart', true);
          } else {
            this.currentTabName = 'USBPart';
          }
          this.operateOptions.addNew = true;
        }
      });
    },
    changeAddOrDel: function(key, value) {
      if (key === 'delTab') {
        this.delTab(this.currentTabName);
      } else {
        this.operateOptions[key] = value;
      }
    },
    updateVmDate: function(part, info) {
      if (part === 'vmConfigPart') {
        let keys = Object.keys(info);
        keys.forEach(x => {
          this.$set(this.editVmData, x, info[x]);
        });
      } else if (part === 'DiskPart') {
        this.$set(this.editVmData, 'disks', info);
      } else if (part === 'FPPart') {
        info.path = info.path === '无' ? '' : info.path;
        this.$set(this.editVmData, 'floppy', info);
      } else if (part === 'USBPart') {
        this.$set(this.editVmData, 'usbs', info);
      } else if (part === 'GHCARDPart') {
        this.$set(this.editVmData, 'graphicsCardModel', info.graphicsCardModel);
        this.$set(this.editVmData, 'graphicsCardMemory', info.graphicsCardMemory);
      } else if (part === 'cpuPart') {
        let keys = Object.keys(info);
        keys.forEach(x => {
          this.$set(this.editVmData, x, info[x]);
        });
      } else if (part === 'OSPart') {
        this.osInfo = info;
      } else if (part === 'vmGPUPart') {
        this.$set(this.editVmData, 'gpus', info);
      } else if (part === 'CDPart') {
        this.$set(this.editVmData, 'cdrom', info);
      } else if (part === 'MemoryPart') {
        let keys = Object.keys(info);
        keys.forEach(x => {
          this.$set(this.editVmData, x, info[x]);
        });
      } else if (part === 'NetPart') {
        this.$set(this.editVmData, 'nics', info);
      } else if (part === 'PCIPart') {
        this.$set(this.editVmData, 'vmPics', info);
      } else if (part === 'FPGAPart') {
        this.$set(this.editVmData, 'fpgas', info);
      }
      if (this.modetype2 === 'addVm' || this.modetype2 === 'importVm') {
        this.$emit('changeInfo', this.editVmData);
      }
    },
    addHard(event) {
      this.$menu(event, {
        placement: 'top',
        list: this.addHardList
      });
    },
    checkTabs(newName, oldName) {
      let comps = this.$refs.tabsCon;
      let thisValid;
      let canChange = true;
      if (oldName) {
        for (let i = 0; i < comps.length; i++) {
          if (comps[i].ref === oldName) {
            thisValid = comps[i];
            break;
          }
        }
        if (thisValid && thisValid.validTab) {
          return thisValid.validTab();
        }
      }
      return canChange;
    }
  }
};

</script>
<style>
</style>
